﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Messaging;
using MessageCommon;
using System.Diagnostics;

namespace ReceiveClient
{
    public class ClientReceiveMSG
    {
        Timer m_timReceive;
        MessageQueue m_objLocalQueue;

        public ClientReceiveMSG()
        {
            m_timReceive = new Timer();
            m_timReceive.Interval = 1000;
            m_timReceive.Tick += new EventHandler(TimerReceive_Tick);
            m_timReceive.Enabled = false;
            m_objLocalQueue=new MessageQueue(GlobalConst.MESSAGELOCALPATH);
            m_objLocalQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(LocalMSGQueue_ReceiveCompleted);
        }

        void LocalMSGQueue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            try
            {
                // Connect to the queue.
                MessageQueue mq = (MessageQueue)sender;

                // End the asynchronous receive operation.
                System.Messaging.Message m = mq.EndReceive(e.AsyncResult);
                m.Formatter = new XmlMessageFormatter(new Type[] { typeof(PushMessage) });
                PushMessage msgInfo = m.Body as PushMessage;
                NotificationCenter.PubicEventCenter.RaiseOneMsgReceiveFinishedEvent(msgInfo);
            }
            catch (MessageQueueException)
            {
                // Handle sources of MessageQueueException.
            }
            m_objLocalQueue.BeginReceive();
        }

        public void ReceiveOffLineMSG()
        {

        }

        public void ReceiveOnLineMSG()
        {
            m_objLocalQueue.BeginReceive();
            //m_timReceive.Enabled = true;
            //m_timReceive.Start();
        }

        public void StopReceiveMsg()
        {
            m_timReceive.Stop();
        }

        void TimerReceive_Tick(object sender, EventArgs e)
        {
            Debug.WriteLine("finish BeginReceive");
            m_objLocalQueue.BeginReceive();
        }
    }
}
